package com.rbac.admin.service.system.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.admin.dto.MenuDTO;
import com.rbac.admin.entity.system.SystemMenu;
import com.rbac.admin.mapper.system.MenuMapper;
import com.rbac.admin.service.system.MenuService;
import com.rbac.admin.util.MenuConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单服务实现类
 *
 * @author rbac-admin
 * @since 2024-07-18
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, SystemMenu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<SystemMenu> getMenusByUserId(String userId) {
        List<SystemMenu> menus = menuMapper.selectMenusByUserId(userId);
        System.out.println("查询到的原始菜单: " + menus);
        return buildMenuTree(menus);
    }
    
    @Override
    public List<MenuDTO> getMenuDTOsByUserId(String userId) {
        // 先获取原始菜单数据
        List<SystemMenu> menus = menuMapper.selectMenusByUserId(userId);
        // 转换为DTO
        List<MenuDTO> dtoList = MenuConverter.convertToDTOList(menus);
        System.out.println("转换后的DTO数量: " + dtoList.size());
        for (MenuDTO dto : dtoList) {
            System.out.println("DTO项: id=" + dto.getId() + ", name=" + dto.getName() + ", type=" + dto.getType());
        }
        
        // 构建树结构
        List<MenuDTO> treeList = MenuConverter.buildTree(dtoList);
        System.out.println("构建的树结构数量: " + treeList.size());
        return treeList;
    }

    @Override
    public List<SystemMenu> getMenusByRoleId(String roleId) {
        return menuMapper.selectMenusByRoleId(roleId);
    }
    
    @Override
    public List<MenuDTO> getMenuDTOsByRoleId(String roleId) {
        // 先获取原始菜单数据
        List<SystemMenu> menus = menuMapper.selectMenusByRoleId(roleId);
        // 转换为DTO
        List<MenuDTO> dtoList = MenuConverter.convertToDTOList(menus);
        // 构建树结构
        return MenuConverter.buildTree(dtoList);
    }
    
    @Override
    public List<String> getMenuIdsByRoleId(String roleId) {
        return menuMapper.selectMenuIdsByRoleId(roleId);
    }

    @Override
    public List<String> getPermissionsByUserId(String userId) {
        return menuMapper.selectPermissionsByUserId(userId);
    }

    @Override
    public List<SystemMenu> getMenusByUserIdAndRoleId(String userId, String roleId) {
        List<SystemMenu> menus = menuMapper.selectMenusByUserIdAndRoleId(userId, roleId);
        System.out.println("查询到的角色专用菜单: userId=" + userId + ", roleId=" + roleId + ", menuCount=" + menus.size());
        return buildMenuTree(menus);
    }

    @Override
    public List<MenuDTO> getMenuDTOsByUserIdAndRoleId(String userId, String roleId) {
        // 先获取原始菜单数据
        List<SystemMenu> menus = menuMapper.selectMenusByUserIdAndRoleId(userId, roleId);
        System.out.println("角色切换 - 查询到的原始菜单数量: " + menus.size() + ", userId=" + userId + ", roleId=" + roleId);

        // 转换为DTO
        List<MenuDTO> dtoList = MenuConverter.convertToDTOList(menus);
        System.out.println("角色切换 - 转换后的DTO数量: " + dtoList.size());

        // 构建树结构
        List<MenuDTO> treeList = MenuConverter.buildTree(dtoList);
        System.out.println("角色切换 - 构建的树结构数量: " + treeList.size());
        return treeList;
    }

    @Override
    public List<String> getPermissionsByUserIdAndRoleId(String userId, String roleId) {
        return menuMapper.selectPermissionsByUserIdAndRoleId(userId, roleId);
    }

    @Override
    public List<MenuDTO> getAllMenuDTOs(String name, Integer type, Integer status, String parentId) {
        // 构建查询条件
        List<SystemMenu> menus;
        
        // 如果有查询条件，则使用条件查询
        if ((name != null && !name.isEmpty()) || type != null || status != null || (parentId != null && !parentId.isEmpty())) {
            menus = this.lambdaQuery()
                .like(name != null && !name.isEmpty(), SystemMenu::getName, name)
                .eq(type != null, SystemMenu::getType, type)
                .eq(status != null, SystemMenu::getStatus, status)
                .eq(parentId != null && !parentId.isEmpty(), SystemMenu::getParentId, parentId)
                .orderByAsc(SystemMenu::getSort)
                .list();
            
            System.out.println("按条件查询到的菜单数量: " + menus.size());
        } else {
            // 无条件，获取所有菜单
            menus = this.list();
            System.out.println("查询所有菜单，数量: " + menus.size());
        }
        
        // 转换为DTO
        List<MenuDTO> dtoList = MenuConverter.convertToDTOList(menus);
        
        // 如果没有指定条件，返回树形结构；否则返回扁平列表
        if ((name == null || name.isEmpty()) && type == null && status == null && (parentId == null || parentId.isEmpty())) {
            return MenuConverter.buildTree(dtoList);
        } else {
            return dtoList;
        }
    }

    @Override
    public List<SystemMenu> buildMenuTree(List<SystemMenu> menus) {
        if (menus == null || menus.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 按sort字段对整个列表进行预排序
        List<SystemMenu> sortedList = new ArrayList<>(menus);
        sortedList.sort((a, b) -> {
            Integer sortA = a.getSort() != null ? a.getSort() : 0;
            Integer sortB = b.getSort() != null ? b.getSort() : 0;
            return sortA.compareTo(sortB);
        });
        
        // 按ID分组
        Map<String, SystemMenu> menuMap = new HashMap<>();
        for (SystemMenu menu : sortedList) {
            menuMap.put(String.valueOf(menu.getId()), menu);
        }
        
        // 构建树结构
        List<SystemMenu> rootList = new ArrayList<>();
        for (SystemMenu menu : sortedList) {
            // 如果是根节点，直接添加到结果列表
            if (menu.getParentId() == null || "0".equals(menu.getParentId())) {
                rootList.add(menu);
            } else {
                // 子节点，添加到父节点的children集合
                SystemMenu parent = menuMap.get(menu.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(menu);
                }
            }
        }
        
        // 对每个父节点的子节点列表进行排序
        for (SystemMenu menu : menuMap.values()) {
            if (menu.getChildren() != null && !menu.getChildren().isEmpty()) {
                menu.getChildren().sort((a, b) -> {
                    Integer sortA = a.getSort() != null ? a.getSort() : 0;
                    Integer sortB = b.getSort() != null ? b.getSort() : 0;
                    return sortA.compareTo(sortB);
                });
            }
        }
        
        return rootList;
    }
} 